<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item prop="username" label="用户名称">
          <el-input
            v-model="queryParams.username"
            placeholder="用户名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="mb-10px">
        <el-button type="success" icon="plus" @click="handleOpenDialog()">新增</el-button>
        <el-button type="danger" :disabled="ids.length === 0" icon="delete" @click="handleDelete()">
          删除
        </el-button>
      </div>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="UserList"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="用户名称" align="center" prop="username" width="180" />
        <el-table-column label="姓名" align="center" prop="name" width="180" />
        <el-table-column label="角色名称" align="center" prop="role_name" width="180" />
        <el-table-column label="用户头像" align="center" width="120">
          <template #default="scope">
            <el-avatar shape="square" :src="scope.row.avatar" />
          </template>
        </el-table-column>
        <el-table-column label="手机号码" align="center" prop="phone" width="120" />
        <el-table-column label="创建时间" align="center" prop="createTime" min-width="180">
          <template #default="scope">
            {{ formatTime(scope.row.create_time) }}
          </template>
        </el-table-column>
        <el-table-column label="更新时间" align="center" prop="updateTime" min-width="180">
          <template #default="scope">
            {{ formatTime(scope.row.update_time) }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" align="center" label="操作" width="180">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              icon="edit"
              @click="handleOpenDialog(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              link
              icon="delete"
              @click="handleDelete(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>

    <!-- 用户表单弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="500px"
      @close="handleCloseDialog"
    >
      <el-form ref="UserFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="用户名称" prop="username">
          <el-input v-model="formData.username" placeholder="请输入用户名称" />
        </el-form-item>
        <el-form-item label="登录密码" prop="password">
          <el-input v-model="formData.password" type="password" placeholder="请输入登录密码" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="formData.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="角色" prop="role_id">
          <el-select v-model="formData.role_id" placeholder="请输入角色">
            <el-option
              v-for="item in roleOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="头像">
          <SingleImageUpload v-model="formData.avatar" />
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入手机号码" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "User",
  inheritAttrs: false,
});

import UserAPI from "@/api/system/user";
import RoleAPI from "@/api/system/role";
import { formatTime } from "@/utils/time";
const queryFormRef = ref(ElForm);
const UserFormRef = ref(ElForm);
const permTreeRef = ref<InstanceType<typeof ElTree>>();

const loading = ref(false);
const ids = ref<number[]>([]);
const total = ref(0);

const queryParams = reactive<any>({
  pageNum: 1,
  pageSize: 10,
});

// 用户表格数据
const UserList = ref<any[]>();
// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
});
// 用户表单
const formData = reactive<any>({
  id: null,
  username: "",
  password: "",
  name: "",
  phone: "",
  role_id: "",
  avatar: "",
});

const rules = reactive({
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
  name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  phone: [{ required: true, message: "请输入手机号码", trigger: "blur" }],
  role_id: [{ required: true, message: "请选择角色", trigger: "blur" }],
  avatar: [{ required: true, message: "请选择头像", trigger: "blur" }],
});

// 选中的用户
interface CheckedUser {
  id?: number;
  name?: string;
}
const checkedUser = ref<CheckedUser>({});

// 查询
function handleQuery() {
  loading.value = true;
  UserAPI.getPage(queryParams)
    .then((data) => {
      UserList.value = data.list;

      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

// 行复选框选中
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.UserNum);
}
const roleOptions: any = ref([]);
// 打开用户弹窗
function handleOpenDialog(Good?: any) {
  dialog.visible = true;
  RoleAPI.getOptions().then((data) => {
    roleOptions.value = data;
  });
  if (Good) {
    dialog.title = "修改用户";
    // UserAPI.getFormData(UserId).then((data) => {
    Object.assign(formData, Good);
    // });
  } else {
    dialog.title = "新增用户";
  }
}

// 提交用户表单
function handleSubmit() {
  UserFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const UserId = formData.id;
      if (UserId) {
        UserAPI.update(formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        UserAPI.add(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  UserFormRef.value.resetFields();
  UserFormRef.value.clearValidate();
  formData.username = "";
  formData.password = "";
  formData.name = "";
  formData.phone = "";
  formData.role_id = "";
  formData.avatar = "";
}

// 删除用户
function handleDelete(UserId?: number) {
  const UserIds = [UserId || ids.value].join(",");
  if (!UserIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      UserAPI.deleteByIds(UserIds)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

onMounted(() => {
  handleQuery();
});
</script>
